import { defineNuxtRouteMiddleware, navigateTo, useRequestHeaders } from '#app'

export default defineNuxtRouteMiddleware(async (to) => {
  // only enforce for admin-page and ai-tools routes
  if (!to.path.startsWith('/admin-page') && !to.path.startsWith('/ai-tools')) return

  // collect admin key from server SSR headers or client localStorage
  let headers: Record<string, string> = {}
  if (process.server) {
    const reqHeaders = useRequestHeaders(['x-admin-key'])
    headers['x-admin-key'] = (reqHeaders && reqHeaders['x-admin-key']) || ''
  } else {
    headers['x-admin-key'] = (typeof window !== 'undefined' && localStorage.getItem('admin_key')) || ''
  }

  try {
    const res: any = await $fetch('/api/admin-routes', { method: 'GET', headers })
    if (res && Array.isArray(res.routes)) {
      const entry = res.routes.find((r: any) => r.path === to.path)
      if (entry && entry.allowed === false) {
        return navigateTo('/403')
      }
    }
  } catch (e) {
    // If the routes API fails, do not block by default. Log to console for debugging.
    if (process.client) console.error('admin-access middleware error:', e)
  }
})
